#include "frmmain.h"
#include "ui_frmmain.h"
#include "httpserver.h"
#include "qdebug.h"

frmMain::frmMain(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::frmMain)
{
    ui->setupUi(this);

    HttpServer *server = new HttpServer(this);
    connect(server, SIGNAL(receiveData(QString)), this, SLOT(receiveData(QString)));

    int port = 8080;
#if (QT_VERSION > QT_VERSION_CHECK(5,0,0))
    bool ok = server->listen(QHostAddress::AnyIPv4, port);
#else
    bool ok = server->listen(QHostAddress::Any, port);
#endif
    qDebug() << ok;
}

frmMain::~frmMain()
{
    delete ui;
}

void frmMain::receiveData(const QString &data)
{
    //取出二维码内容
    QString str = data.split("=").last();
    str = QString(QByteArray::fromPercentEncoding(str.toLatin1()));

    //当前焦点多行文本框设置内容,如果没有一个焦点则取第一个
    bool exist = false;
    QList<QTextEdit *> txts = this->findChildren<QTextEdit *>();
    foreach (QTextEdit *txt, txts) {
        if (txt->hasFocus()) {
            txt->setPlainText(str);
            exist = true;
            break;
        }
    }

    if (!exist) {
        ui->txt1->setPlainText(str);
    }
}

void frmMain::on_btnClear_clicked()
{
    QList<QTextEdit *> txts = this->findChildren<QTextEdit *>();
    foreach (QTextEdit *txt, txts) {
        txt->clear();
    }
}
